import store from "@/store"
import common from "@/common/global"
import commonData from "@/common/data"
// const SocketUrl="ws://82.157.204.174:2023/chat/"
// const musicUrl = "http://82.157.204.174:2023/File/getfile/record/Tips/tips.mp3"

const SocketUrl="ws://localhost:9090/chat/"
const musicUrl = commonData.ip +  "File/getfile/record/Tips/tips.mp3"

let that
class Chat{
    constructor(data){
      this.uid = data.uid || 0
      this.token=data.token
      this.SocketUrl=SocketUrl + data.uid 
      that=this
      this.init()
    }
    // 连接后端聊天服务器
    init(){
        this.Socket = new WebSocket(this.SocketUrl);  //创建一个websocket服务
        this.Socket.onopen ;  //开启服务
        this.Socket.onmessage = this.onmessage//收到消息
        this.Socket.onerror=this.onerror //错误连接
    }
    playMusic(){
        let mp3 = new Audio();
        mp3.src = musicUrl
        mp3.play();
        mp3.addEventListener('ended', () => {
            mp3.pause()
        });
       
    }
    //收到消息
    onmessage(message){
        let data= JSON.parse(message.data)
      
        if(data.type == 1){ //搜到消息
            common.AddInform({type:'success',content:'你收到一条消息'})
            store.commit('Chat/ADDCHATCONTENT',JSON.parse(data.content))
            that.playMusic()
        }
        else if(data.type == 2){ //收到好友请求
            common.AddInform({type:'success',content:'你收到一条好友申请'})
            store.dispatch('Inform/refreshFriendRecord',that.uid)
            that.playMusic()
        }
    }
    //onerror
    onerror(message){
        console.log('错误连接')
    }

}
export default Chat